//
//  GSConnectionDialog.m
//  AgileNYC
//
//  Created by German on 11.06.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSDialogsManager.h"
#import "SGSAppDelegate.h"
#import "SGSAppConsts.h"
#import "SGSUtils.h"
#import "SGSServerManager.h"
#import "SGSModelsManager.h"

#if APPLE_STANDARD

@interface GSDialogsManager () <UIAlertViewDelegate, UITextFieldDelegate>
        @property (strong,nonatomic) UIAlertView * dlgConnection;
        @property (strong,nonatomic) UIAlertView * dlgRequest;
        @property (strong,nonatomic) UIAlertView * dlgError;

#else

#import "URBAlertView.h"


@interface SGSDialogsManager () <UIAlertViewDelegate, UITextFieldDelegate>
        @property (strong, nonatomic) URBAlertView * dlgConnection;
        @property (strong, nonatomic) URBAlertView * dlgRequest;
        @property (strong, nonatomic) URBAlertView * dlgError;

#endif
        @property (weak, nonatomic) UITextField * dialogInputView;
        @property (copy, nonatomic) GSConnectionDialogCompletionBlock connectionDialogBlock;
        @property (copy, nonatomic) GSRequestDialogCompletionBlock requestDialogCompletionBlock;
        @property (copy, nonatomic) GSErrorDialogCompletionBlock errorDialogBlock;

        @property (copy, nonatomic) URBHandlerBlock handlerBlock;

        @property(strong, nonatomic) dispatch_queue_t dialogQueue;
        @property (strong, nonatomic) dispatch_semaphore_t dialogSemaphore;

@end


@implementation SGSDialogsManager

+(SGSDialogsManager*) dialogsManager {
    
    static SGSDialogsManager * dialog = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dialog = [[SGSDialogsManager alloc] init];
        
    });
    
    return dialog;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {

#if APPLE_STANDARD
        //Connection dialog
        self.dlgConnection = [[UIAlertView alloc] init];
        self.dlgConnection.alertViewStyle = UIAlertViewStylePlainTextInput;
        
        self.dialogInputView = [self.dlgConnection textFieldAtIndex:0];
        
        // Connection request dialog
        self.dlgRequest = [[UIAlertView alloc] init];
        self.dlgRequest.alertViewStyle = UIAlertViewStyleDefault;
        
        // Connection request dialog
        self.dlgError = [[UIAlertView alloc] init];
        self.dlgError.alertViewStyle = UIAlertViewStyleDefault;
        
        self.dlgConnection.delegate = self;
        self.dlgRequest.delegate = self;
        self.dlgError.delegate = self;
#else
        NSValue *shadowOffset = [NSValue valueWithUIOffset:UIOffsetMake(0.0, 0.0)];
        NSDictionary *titleTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:18.0f],
                                              NSForegroundColorAttributeName:COLOR_MAIN_BLACK,
                                              NSShadowAttributeName:[UIColor whiteColor],
                                              NSShadowAttributeName:shadowOffset};

        NSDictionary *messageTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:15.0f],
                                              NSForegroundColorAttributeName:COLOR_MAIN_BLACK,
                                              NSShadowAttributeName:[UIColor whiteColor],
                                              NSShadowAttributeName:shadowOffset};

        NSDictionary *buttonTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0f],
                                                NSForegroundColorAttributeName:COLOR_MAIN_BLACK,
                                                NSShadowAttributeName:[UIColor whiteColor],
                                                NSShadowAttributeName:shadowOffset};

        NSDictionary *cancelButtonTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0f],
                                               NSForegroundColorAttributeName:COLOR_MAIN_BLACK,
                                               NSShadowAttributeName:[UIColor whiteColor],
                                               NSShadowAttributeName:shadowOffset};
        
        
        [[URBAlertView appearance] setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:1.0]];
        [[URBAlertView appearance] setBackgroundGradation:0.05];
        [[URBAlertView appearance] setStrokeColor:[UIColor colorWithWhite:0.35 alpha:1.0]];
        [[URBAlertView appearance] setStrokeWidth:1.0];
        [[URBAlertView appearance] setTitleTextAttributes:titleTextAttributes];
        [[URBAlertView appearance] setMessageTextAttributes:messageTextAttributes];
        [[URBAlertView appearance] setButtonBackgroundColor:[UIColor colorWithWhite:0.8 alpha:1.0]];
        [[URBAlertView appearance] setButtonStrokeColor:COLOR_MAIN_WHITE];
        [[URBAlertView appearance] setButtonTextAttributes:buttonTextAttributes forState:UIControlStateNormal];
        [[URBAlertView appearance] setCancelButtonTextAttributes:cancelButtonTextAttributes forState:UIControlStateNormal];
        
        __weak __typeof(self) weakSelf = self;
        
        self.handlerBlock = ^(NSInteger buttonIndex, URBAlertView *alertView) {
            __strong __typeof(self) self = weakSelf;
            [self alertView:(UIAlertView*)alertView clickedButtonAtIndex:buttonIndex];
            [alertView hide];
        };
        
#endif

        self.dlgConnection.title = Connection_Dialog_Title;
   	    self.dlgConnection.message = Connection_Dialog_Message;
        
	    [self.dlgConnection addButtonWithTitle: Connect_Button_Title];
	    [self.dlgConnection addButtonWithTitle: Cancel_Button_Title];

        self.dialogInputView.textAlignment = NSTextAlignmentCenter;
        self.dialogInputView.keyboardType = UIKeyboardTypeNumberPad;
        self.dialogInputView.delegate = self;
        
        self.dlgRequest.title = Connection_Request_Title;
        
	    [self.dlgRequest addButtonWithTitle: Accept_Button_Title];
	    [self.dlgRequest addButtonWithTitle: Ignore_Button_Title];
	    [self.dlgRequest addButtonWithTitle: View_Info_Button_Title];
        
        self.dlgError.title = Error_Dialog_Title;
        
        [self.dlgError addButtonWithTitle: Ok_Button_Title];

        self.dialogQueue = dispatch_queue_create("uz.softlegion.AgileNYC.dialogqueue", NULL);
        self.dialogSemaphore = dispatch_semaphore_create(1);
    }
    return self;
}

- (void)dealloc
{
    self.dlgConnection = nil;
    self.dlgRequest = nil;
    self.dlgError = nil;
    self.dialogQueue = nil;
}

-(void) showConnectionDialog:(NSString*) textIntoField
                  onComplete:(GSConnectionDialogCompletionBlock) completetionBlock {
    
    //if (![self.theLock tryLock]) return;
    
    self.connectionDialogBlock = completetionBlock;
    
    dispatch_async(self.dialogQueue, ^{
        dispatch_semaphore_wait(self.dialogSemaphore, DISPATCH_TIME_FOREVER);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createConnectionDialog];
        });
        
    });
    
}

-(void) showRequestDialog:(NSString*) requesterName
               onComplete:(GSRequestDialogCompletionBlock) completetionBlock {
    
    //if (![self.theLock tryLock]) return;
    
    self.requestDialogCompletionBlock = completetionBlock;
    
    dispatch_async(self.dialogQueue, ^{
        dispatch_semaphore_wait(self.dialogSemaphore, DISPATCH_TIME_FOREVER);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createRequestDialog:requesterName];
        });
        
    });

}

-(void) showSimpleDialog:(NSString*) title message:(NSString*) message
              onComplete:(GSErrorDialogCompletionBlock) completetionBlock {

    //if (![self.theLock tryLock]) return;
    
    self.errorDialogBlock = completetionBlock;
    
    dispatch_async(self.dialogQueue, ^{
        dispatch_semaphore_wait(self.dialogSemaphore, DISPATCH_TIME_FOREVER);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createSimpleDialog:message withTitle:title];
        });
        
    });
}

#pragma mark - Connection Dialog <TSAlertViewDelegate>

#if APPLE_STANDARD
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
#else
- (void)alertView:(URBAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
#endif
    
      if ([alertView isEqual:self.dlgConnection]) { //Connection
          if (self.connectionDialogBlock) {
              self.connectionDialogBlock(buttonIndex, self.dialogInputView.text);
          }
      } else if ([alertView isEqual:self.dlgRequest]) { //Connection request
          if (self.requestDialogCompletionBlock) {
              self.requestDialogCompletionBlock(buttonIndex);
          }
      } else if ([alertView isEqual:self.dlgError]) { //Error
          if (self.errorDialogBlock) {
              self.errorDialogBlock();
          }
      }
    
    //[self.theLock unlock];
    dispatch_semaphore_signal(self.dialogSemaphore);
}

#pragma mark - UITextFieldDelegate
    
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
        
    return YES;
}
    
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString * replacedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    NSCharacterSet * set = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    
    NSArray * words = [replacedString componentsSeparatedByCharactersInSet:set];
    
    if ([words count]>1) {
        return NO;
    }
    
    if (replacedString.length>4) {
        return NO;
    }
    
    if (replacedString.length==4) {
        textField.text = replacedString;
        [textField resignFirstResponder];
        return NO;
    }
    
    return YES;
}

#pragma mark - Internal Functions
    
-(void) createConnectionDialog {
    
    GSLog(GSLogInfo,@"showConnectionDialog executed");
    
#if !APPLE_STANDARD
    self.dlgConnection = [[URBAlertView alloc] init];
    [self.dlgConnection addTextFieldWithPlaceholder:@"" secure:NO];
    self.dialogInputView = [self.dlgConnection.textFields objectAtIndex:0];
    [self.dialogInputView setFont:[UIFont fontWithName:@"HelveticaNeue" size:25]];
    self.dialogInputView.textAlignment = NSTextAlignmentCenter;
    self.dialogInputView.keyboardType = UIKeyboardTypeNumberPad;
    self.dialogInputView.delegate = self;
    
    [self.dlgConnection setHandlerBlock:self.handlerBlock];
    [self.dlgConnection addButtonWithTitle: Connect_Button_Title];
    [self.dlgConnection addButtonWithTitle: Cancel_Button_Title];
#endif
    
    self.dlgConnection.title = Connection_Dialog_Title;
    self.dlgConnection.message = Connection_Dialog_Message;
    
#if APPLE_STANDARD
    [self.dlgConnection show];
#else
    [self.self.dlgConnection showWithAnimation:URBAlertAnimationFade];
#endif
}
    
-(void) createRequestDialog:(NSString*) requesterName {
    GSLog(GSLogInfo,@"showConnectionDialog executed");
    
#if !APPLE_STANDARD
    self.dlgRequest = [[URBAlertView alloc] init];
    [self.dlgRequest setHandlerBlock:self.handlerBlock];
    [self.dlgRequest addButtonWithTitle: Accept_Button_Title];
    [self.dlgRequest addButtonWithTitle: Ignore_Button_Title];
    [self.dlgRequest addButtonWithTitle: View_Info_Button_Title];
        
#endif
    self.dlgRequest.title = Connection_Request_Title;
    self.dlgRequest.message = [NSString stringWithFormat:Connection_Request_Message, requesterName];
    
#if APPLE_STANDARD
    [self.dlgRequest show];
#else
    [self.self.dlgRequest showWithAnimation:URBAlertAnimationFade];
#endif
 
}
    
-(void) createSimpleDialog:(NSString*) message withTitle:(NSString*) title {
    
    GSLog(GSLogInfo,@"showErrorDialog executed");
    
#if !APPLE_STANDARD
    self.dlgError = [[URBAlertView alloc] init];
    [self.dlgError setHandlerBlock:self.handlerBlock];
    [self.dlgError addButtonWithTitle: Ok_Button_Title];
#endif
    
    self.dlgError.title = title;
    self.dlgError.message = message;
    
#if APPLE_STANDARD
    [self.dlgError show];
#else
    [self.dlgError  showWithAnimation:URBAlertAnimationFade];
#endif
}
    
@end
